package com.sgb.kjwl.view.ui.activity.transport;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;

import androidx.databinding.DataBindingUtil;

import android.os.Handler;
import android.os.Message;

import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityMainCitiesBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.self.RunningCityEntity;
import com.sgb.kjwl.model.entity.self.RunningCityPEntity;
import com.sgb.kjwl.model.entity.self.SelectPotionEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.ui.adapter.transport.MainCitiesAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.transport.MainCitiesModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class MainCitiesActivity extends AppActivity {


    ActivityMainCitiesBinding binding;
    private MainCitiesAdapter mainCitiesAdapter;
    @Inject
    MainCitiesModel viewModel;
    UserMsgEntity data;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    private boolean isLoaded = false;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private int currentClickPosition;
    private List<SelectPotionEntity> potionEntityList;
    MutableLiveData<Boolean> ldChangeList = new MutableLiveData<>();

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainCitiesActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main_cities);
        binding.setOnClick(this);
        binding.include.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.include.titleView.setText("常跑线路");
        if (mainCitiesAdapter == null) {
            mainCitiesAdapter = new MainCitiesAdapter(getActivity(), null);
        }
        mainCitiesAdapter.setItemChildCLickListener(new MainCitiesAdapter.ItemChildCLickListener() {
            @Override
            public void deleteOne(int position) {
                mainCitiesAdapter.getDatas().remove(position);
                mainCitiesAdapter.notifyDataSetChanged();
                ldChangeList.postValue(true);
            }

            @Override
            public void selectCity(LinearLayout root, int position) {
                currentClickPosition = position;
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
            }
        });
        ldChangeList.observe(this, isChange -> {
            if (mainCitiesAdapter.getItemCount() < 6) {
                binding.addBtn.setClickable(true);
                binding.imageView13.setAlpha(1f);
                binding.tvAdd.setAlpha(1f);
            } else {
                binding.addBtn.setClickable(false);
                binding.imageView13.setAlpha(0.5f);
                binding.tvAdd.setAlpha(0.5f);
            }
        });
        binding.list.setLayoutManager(new LinearLayoutManager(this));
        binding.list.setAdapter(mainCitiesAdapter);
        binding.addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mainCitiesAdapter.getItemCount() < 6) {
                    RunningCityEntity runningCityEntity = new RunningCityEntity();
                    mainCitiesAdapter.addData(runningCityEntity);
                    SelectPotionEntity selectPotionEntity = new SelectPotionEntity();
                    potionEntityList.add(selectPotionEntity);
                    ldChangeList.postValue(true);
                }
            }
        });
        binding.textView37.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                List<RunningCityEntity> cities = new ArrayList<>();
                if (mainCitiesAdapter.getDatas().size() > 0) {

                    for (RunningCityEntity entity : mainCitiesAdapter.getDatas()) {
                        if (!TextUtils.isEmpty(entity.getCityName())) {
                            cities.add(entity);
                        }
                    }

                }
                String freight = binding.etReleaseCargoFreight.getText().toString();
                if (!TextUtils.isEmpty(freight)) {
                    int price = Integer.valueOf(freight);
                    if (price < 1) {
                        MToast.showToast(MainCitiesActivity.this, "意向价格不能低于1");
                        return;
                    }
                    if (price > 99999) {
                        MToast.showToast(MainCitiesActivity.this, "意向价格不能高于99999");
                        return;
                    }

                }
                viewModel.entity.get().setFreight(freight);
                if (cities.size() > 0) {
                    viewModel.entity.get().setSaveWayDTOList(cities);
                    if (data != null) {
                        if (data.isDriverAuth()) {
                            switch (data.isDriverAuth() ? "SUCCESS" : "NONE") {
                                case "FAIL":
                                    MToast.showToast(MainCitiesActivity.this, "司机认证不通过，不能进行操作");
                                    break;
                                case "STANDBY":
                                    MToast.showToast(MainCitiesActivity.this, "司机认证审核中，不能进行操作");
                                    break;
                                case "NONE":
                                    MToast.showToast(MainCitiesActivity.this, "暂无权限，请进行司机认证");
                                    break;
                                default:
                                    viewModel.saveWay();
                                    break;
                            }
                        }else{
                            MToast.showToast(MainCitiesActivity.this, "暂无权限，请进行司机认证");
                        }
                    }
                } else {
                    MToast.showToast(MainCitiesActivity.this, "请设置路线");
                }

            }
        });
    }

    @Override
    protected void init() {
        super.init();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        potionEntityList = new ArrayList<>();
        viewModel.frequentlyUsedWay();
        viewModel.getUserInfo();
        viewModel.entity.set(new RunningCityPEntity());

    }


    public void showCityPop() {
        UiUtil.hide(this);
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(MainCitiesActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                SelectPotionEntity selectPotionEntity = new SelectPotionEntity();
                selectPotionEntity.setCityPosition1(options1);
                selectPotionEntity.setCityPosition2(options2);
                potionEntityList.set(currentClickPosition, selectPotionEntity);
//                if (runningCityEntity == null){
                RunningCityEntity runningCityEntity = new RunningCityEntity();
//                }
                runningCityEntity.setCityName(opt2.get(options1).get(options2).getName());
                runningCityEntity.setCityNo(opt2.get(options1).get(options2).getNo());
                runningCityEntity.setProvinceName(addressEntityList.get(options1).getName());
                runningCityEntity.setProvinceNo(addressEntityList.get(options1).getNo());
                mainCitiesAdapter.getDatas().set(currentClickPosition, runningCityEntity);
                mainCitiesAdapter.notifyDataSetChanged();
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2);//opt3
        cityOption.setSelectOptions(potionEntityList.get(currentClickPosition).getCityPosition1(), potionEntityList.get(currentClickPosition).getCityPosition2());//cityPosition3
        cityOption.show();
    }

    public void showAddressPop
            (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    public void getSetWay(RunningCityPEntity entity) {
        List<RunningCityEntity> cities = entity.getSaveWayDTOList();
        if (entity != null) {
            viewModel.entity.set(entity);
            if (!TextUtils.isEmpty(entity.getFreight())) {
                binding.etReleaseCargoFreight.setText(NumberUtil.trim0(entity.getFreight()));
                switch (entity.getFreightUnit()) {
                    case 2:
                        switchFreightMode(1);
                        break;
                    case 3:
                        switchFreightMode(2);
                        break;
                    case 4:
                        switchFreightMode(3);
                        break;
                    default:
                        switchFreightMode(0);

                }
            } else {
                switchFreightMode(3);
            }
        }

        if (cities == null || cities.size() == 0) {
            RunningCityEntity runningCityEntity = new RunningCityEntity();
            cities.add(runningCityEntity);
            SelectPotionEntity selectPotionEntity = new SelectPotionEntity();
            potionEntityList.add(selectPotionEntity);
        } else {
            for (int i = 0; i < cities.size(); i++) {
                SelectPotionEntity selectPotionEntity = new SelectPotionEntity();
                potionEntityList.add(selectPotionEntity);
            }
        }
        mainCitiesAdapter.setDatas(cities);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    public void showAuth(UserMsgEntity data) {
        this.data = data;
    }

    @Override
    public void onClick(View v) {
        if (v == binding.tvReleaseCargoOnce) {
            //防止重复点击
            if (binding.tvReleaseCargoOnce.isSelected()) {
                return;
            }
            switchFreightMode(0);
        } else if (v == binding.tvReleaseCargoWeight) {
            //防止重复点击
            if (binding.tvReleaseCargoWeight.isSelected()) {
                return;
            }
           /* //判断是否填写货重
            if (mEntity.getGoodsWeight() == 0) {
                MToast.showToast(this, "请先至货物信息中填写货重");
                return;
            }*/
            switchFreightMode(1);
        } else if (v == binding.tvReleaseCargoVolume) {
            //防止重复点击
            if (binding.tvReleaseCargoVolume.isSelected()) {
                return;
            }
           /* //判断是否填写体积
            if (mEntity.getGoodsVolume() == 0) {
                MToast.showToast(this, "请先至货物信息中填写货物体积");
                return;
            }*/
            switchFreightMode(2);
        } else if (v == binding.tvReleaseCargoWeightKm) {
            //防止重复点击
            if (binding.tvReleaseCargoWeightKm.isSelected()) {
                return;
            }
            switchFreightMode(3);
        }
    }

    private void switchFreightMode(int position) {
        int count = binding.llReleaseCargoFreightType.getChildCount();
        for (int i = 0; i < count; i++) {
            binding.llReleaseCargoFreightType.getChildAt(i).setSelected(false);
        }
        binding.llReleaseCargoFreightType.getChildAt(position).setSelected(true);
        //设置运费方式
        switch (position) {
            case 0:
                viewModel.entity.get().setFreightUnit(1);
                binding.tvReleaseCargoFreightSuffix.setText("元/趟");
                break;
            case 1:
                viewModel.entity.get().setFreightUnit(2);
                binding.tvReleaseCargoFreightSuffix.setText("元/吨");
                break;
            case 2:
                viewModel.entity.get().setFreightUnit(3);
                binding.tvReleaseCargoFreightSuffix.setText("元/方");
                break;
            case 3:
                viewModel.entity.get().setFreightUnit(4);
                binding.tvReleaseCargoFreightSuffix.setText("元/吨.1公里");
                break;
        }
    }
}